#!/bin/bash

set -e
CMAKE_BUILD_TYPE="$1"
USING_COVERAGE="$2"
USING_XSAN="$3"
COMPILE_VERIFICATION="$4"

CURRENT_PATH=$(cd "$(dirname "$0")"; pwd)
source "${CURRENT_PATH}/build_env.sh"
BUILD_PATH=$(cd "$CURRENT_PATH/../build"; pwd)
CPU_TYPE="$(arch)"
echo "Build ${BUILD_PATH} Type=${CMAKE_BUILD_TYPE}"

[ -d "${BUILD_PATH}" ] && rm -rf "${BUILD_PATH}"
mkdir -p "${BUILD_PATH}"

rm -rf "${OUTPUT_PATH}/memory_bridge"
mkdir -p "${OUTPUT_PATH}/memory_bridge"
cp -rf "${HMM_ROOT_PATH}/interface" "${OUTPUT_PATH}/memory_bridge/include"
echo "copy include success"
cd "${BUILD_PATH}"

if ! cmake "${HMM_ROOT_PATH}" -DCMAKE_INSTALL_PREFIX:STRING="${OUTPUT_PATH}" -DCPU_TYPE="${CPU_TYPE}" \
    -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}" -DHMM_ROOT_PATH="${HMM_ROOT_PATH}" -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
    -DUSING_COVERAGE="${USING_COVERAGE}" -DUSING_XSAN="${USING_XSAN}" -DCOMPILE_VERIFICATION="${COMPILE_VERIFICATION}"; then
    echo "cmake failed"
    exit 1
fi

echo "cmake success"
make clean

if ! make -j 10; then
    echo "make -j 10 failed"
    exit 1
fi

if ! make install; then
    echo "make install failed"
    exit 1
fi

cp -rf "${OUTPUT_PATH}/memory_bridge" "${INSTALL_PATH}/."
if [ -e "${INSTALL_PATH}/memory_bridge/lib/libTopoDetectImpl.so"]; then
    rm -rf "${INSTALL_PATH}/memory_bridge/lib/libTopoDetectImpl.so"
fi
echo "make success"